import Pagination from '@/components/Pagination/index'
import { fetchList,createSoldOrder,saveSoldOrder,closeSoldOrder } from '@/api/sold-order'
import ItemPicker from './components/item-picker'
import UserPicker from './components/user-picker'
import tableRouter from '@/router/modules/table'
import { getSales } from '@/api/salesman'
import { deleteProduct } from '@/api/product'

export default {
  name: 'Sold-Order',
  components: { Pagination, ItemPicker, UserPicker },
  data() {
    return {
      dto: null,
      dto_: null,
      statusOptions: [
        {
          value: '',
          label: '全部'
        }, {
          value: 'RETURNING',
          label: '待寄回'
        }, {
          value: 'SHIPPING',
          label: '待收货'
        }, {
          value: 'FINISHED',
          label: '已完成'
        }, {
          value: 'CLOSED',
          label: '已关闭'
        }
      ],
      orderVisible: false,
      addVisible: false,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: null,
        from_date: null,
        to_date: null,
        state: null,
        salesman: null
      },
      unreceived_amount: 0,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      datetime: null,
      tableList:[],
      nullItem: {
        name:null,
        item_id:null,
        price:null,
        quantity:null,
        total:null
      },
      insertIndex: 0,
      user: null,
      sales_options:[
        {
          value: null,
          label: '不限'
        }
      ],
      salesman:null
    }
  },
  created(){
    this.getList()
    this.getSales()
  },
  methods: {
    getSales: async function() {
      const options = this.sales_options
      const res = await getSales();
      for(const v of res.list){
        options.push({
          value:v.id,
          label:v.nickname
        })
      }
    },
    handleCreate(){
      this.init()
      this.addVisible = true
    },

    init(){
      this.tableList = []
      for(let i = 0; i < 1; i++){
        let temp = this.nullItem
        temp.id = i
        this.tableList.push(temp)
      }
    },

    getList(){
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.orders
        this.total = response.total
        this.unreceived_amount = response.unreceived_amount
        this.listLoading = false
      }).catch(error => {
        this.list = []
        this.total = 0
        this.listLoading = false
        Promise.reject(error)
      })
    },

    getDetail(data){
      this.dto = data
      this.dto_ = JSON.parse(JSON.stringify(data));
      this.orderVisible = true
    },

    handleSearch(){
      if (this.listQuery.keyword == '') {
        this.listQuery.keyword = null
      }
      if (this.listQuery.state == '') {
        this.listQuery.state = null
      }
      if (!this.datetime) {
        this.listQuery.from_date = null
        this.listQuery.to_date = null
      } else {
        this.listQuery.from_date = this.datetime[0]
        this.listQuery.to_date = this.datetime[1]
      }
      this.list = []
      this.total = 0
      this.getList()
    },

    handleSelectChange(){
      const id = this.listQuery2.category
      const list = [{
        value: 0,
        label: '全部'
      }]
      if (id === 0) {
        this.subCategoryOptions = list
      } else {
        const index = this.categoryOptions.findIndex(v => v.value === id)
        const item = this.categoryOptions[index]
        this.subCategoryOptions = list.concat(item.children)
      }
      this.listQuery.sub_category = 0
    },

    removeLine(index){
      if(this.tableList.length > 1){
        this.tableList.splice(index,1)
      }
    },

    addLine(index){
      this.tableList.splice(index + 1,0,this.nullItem)
    },

    updateTotal(index){
      if(parseFloat(this.tableList[index].price) && parseInt(this.tableList[index].quantity)){
        let number = new Number(parseFloat(this.tableList[index].price) * parseInt(this.tableList[index].quantity))
        this.tableList[index].total = number.toFixed(2)
      }else{
        this.tableList[index].total = null
      }
    },

    createOrder() {
      let list = this.tableList
      let user = this.user
      if(!user){
        this.$message({
          showClose: true,
          message: '请选择退货用户',
          type: 'error'
        });
        return
      }
      if(!list || list.length < 1){
        this.$message({
          showClose: true,
          message: '请新增退货列表',
          type: 'error'
        });
        return
      }
      let data = []
      for(let i in list){
        if(list[i].item_id){
          if(!list[i].price || !list[i].quantity){
            this.$message.error('请填写正确的单价和数量');
            return
          }else{
            data.push({
              id:list[i].item_id,
              quantity:list[i].quantity,
              price:list[i].price
            })
          }
        }
      }
      createSoldOrder({
        user_id: this.user.id,
        items:data
      }).then(res => {
        this.init()
        this.handleSearch()
        this.addVisible = false;
        this.$notify({
          title: '成功',
          message: '创建成功',
          type: 'success',
          duration: 2000
        })
      })
    },

    saveOrder() {
      let dto = this.dto
      let dto_ = this.dto_
      let data = []
      for (let i in dto.items) {
        if(dto.items[i].return_state == 'RETURNED' && dto_.items[i].return_state == 'RETURNING'){
          data.push({
            id:dto.items[i].id
          })
        }
      }
      saveSoldOrder(dto.id,{items:data}).then(res => {
        this.init()
        this.handleSearch()
        this.orderVisible = false;
        this.$notify({
          title: '成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      })
    },

    pickItem(index){
      if(!this.user){
        this.$message({
          showClose: true,
          message: '请先选择退货用户',
          type: 'error'
        });
        return
      }
      this.$refs.item_picker.showSelectDialog(index,this.tableList,this.user.id);
    },

    onSelectConfirm(tableList){
      this.tableList = tableList
    },

    pickUser(){
      this.$refs.user_picker.showSelectDialog();
    },

    onSelectUserConfirm(user){
      this.user = user
      this.init()
    },

    handleCloseOrder(row){
      let self = this
      this.$confirm('关闭后会恢复占用极速退款额度并同步关闭关联未付款的付款单，关闭成功无法撤销', '注意', {
        confirmButtonText: '确定关闭',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        closeSoldOrder(row.id).then(response => {
          this.$notify({
            title: '成功',
            message: '关闭成功',
            type: 'success',
            duration: 2000
          })
          self.handleSearch()
        }).catch(error => {
          Promise.reject(error)
        })
      })
    },
  }
}
